package com.suyeer.basic.util;


import org.apache.commons.lang3.StringUtils;

import java.nio.charset.Charset;
import java.util.Base64;

/**
 * @author jun 2018/10/19
 */
public class EmojiUtil {

    public static String encodeIfContainsEmoji(String src, String prefixOfEncoder) {
        if (containsEmoji(src)) {
            return prefixOfEncoder + Base64.getEncoder().encodeToString(src.getBytes());
        }
        return src;
    }

    public static String decodeIfContainsPrefix(String encoder, String prefixOfEncoder) {
        if (StringUtils.isBlank(encoder)) {
            return encoder;
        }
        if (encoder.startsWith(prefixOfEncoder)) {
            encoder = encoder.substring(prefixOfEncoder.length(), encoder.length());
            encoder = new String(Base64.getDecoder().decode(encoder.getBytes()), Charset.defaultCharset());
        }
        return encoder;
    }

    public static String filterEmoji(String src) {
        int len = src.length();
        StringBuilder buf = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char codePoint = src.charAt(i);
            buf.append(isNotEmojiCharacter(codePoint) ? codePoint : "*");
        }
        return buf.toString();
    }

    private static Boolean isNotEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    public static Boolean containsEmoji(String src) {
        if (StringUtils.isBlank(src)) {
            return false;
        }
        Boolean flag = false;
        int len = src.length();
        for (int i = 0; i < len; i++) {
            char codePoint = src.charAt(i);
            if (!isNotEmojiCharacter(codePoint)) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
